#!/usr/bin/env python3

import sys

notes = {
"P": 0,
"C8": 1,
"B7": 2,
"A#7": 3,
"Bb7": 3,
"A7": 4,
"G#7": 5,
"Ab7": 5,
"G7": 6,
"F#7": 7,
"Gb7": 7,
"F7": 8,
"E7": 9,
"D#7": 10,
"Eb7": 10,
"D7": 11,
"C#7": 12,
"Db7": 12,
"C7": 13,
"B6": 14,
"A#6": 15,
"Bb6": 15,
"A6": 16,
"G#6": 17,
"Ab6": 17,
"G6": 18,
"F#6": 19,
"Gb6": 19,
"F6": 20,
"E6": 21,
"D#6": 22,
"Eb6": 22,
"D6": 23,
"C#6": 24,
"Db6": 24,
"C6": 25,
"B5": 26,
"A#5": 27,
"Bb5": 27,
"A5": 28,
"G#5": 29,
"Ab5": 29,
"G5": 30,
"F#5": 31,
"Gb5": 31,
"F5": 32,
"E5": 33,
"D#5": 34,
"Eb5": 34,
"D5": 35,
"C#5": 36,
"Db5": 36,
"C5": 37,
"B4": 38,
"A#4": 39,
"Bb4": 39,
"A4": 40,
"G#4": 41,
"Ab4": 41,
"G4": 42,
"F#4": 43,
"Gb4": 43,
"F4": 44,
"E4": 45,
"D#4": 46,
"Eb4": 46,
"D4": 47,
"C#4": 48,
"Db4": 48,
"C4": 49,
"B3": 50,
"A#3": 51,
"Bb3": 51,
"A3": 52,
"G#3": 53,
"Ab3": 53,
"G3": 54,
"F#3": 55,
"Gb3": 55,
"F3": 56,
"E3": 57,
"D#3": 58,
"Eb3": 58,
"D3": 59,
"C#3": 60,
"Db3": 60,
"C3": 61,
"B2": 62,
"A#2": 63,
"Bb2": 63,
"A2": 64,
"G#2": 65,
"Ab2": 65,
"G2": 66,
"F#2": 67,
"Gb2": 67,
"F2": 68,
"E2": 69,
"D#2": 70,
"Eb2": 70,
"D2": 71,
"C#2": 72,
"Db2": 72,
"C2": 73,
"B1": 74,
"A#1": 75,
"Bb1": 75,
"A1": 76,
"G#1": 77,
"Ab1": 77,
"G1": 78,
"F#1": 79,
"Gb1": 79,
"F1": 80,
"E1": 81,
"D#1": 82,
"Eb1": 82,
"D1": 83,
"C#1": 84,
"Db1": 84,
"C1": 85,
"B0": 86,
"A#0": 87,
"Bb0": 87,
"A0": 88
}

class NoteClass(object):
    def __init__(self, tone, period):
        self.tone = tone
        self.period = period

Music = []

def AppendNote(tone, period):
    if not Music:
        Music.append(NoteClass(tone, period))
    else:
        if tone == Music[-1].tone and (Music[-1].period + period) < 65536:
            Music[-1].period += period
        else:
            Music.append(NoteClass(tone, period))

def PrintMusicArray():
    print("#include <stdint.h>\n\ntypedef struct")
    print("{\n\tuint16_t tone;\n\tuint16_t duration;\n} Note;\n")
    print("volatile Note Music[] =\n{", end="")
    for Note in Music:
        print("\n\t{", Note.tone, ", ", Note.period, "},", end="", sep="")
    print("\n};")

def ParseLine(line):
    if not line.split(" ")[0] in notes:
        return -1
    tone = notes[line.split(" ")[0]]
    period = int(line.split(" ")[1])
    AppendNote(tone, period)
    return 0

if len(sys.argv) != 2:
    print("No argument!")
    exit(1)


with open(sys.argv[1], "r") as file:
    lnum = 0
    for line in file:
        lnum += 1
        if line[0] != ';':
            if ParseLine(line) == -1:
                print("Error at line ", lnum, ":", sep="")
                print(line)
                quit()
PrintMusicArray()

